<script setup lang="ts">
import { ref, onMounted, onUnmounted, watch } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import apiClient from '@/api.ts';
import EasyMDE from 'easymde';
import 'easymde/dist/easymde.min.css';

const route = useRoute();
const router = useRouter();

const title = ref('');
const content = ref('');
const isEditMode = ref(false);
const postId = ref<string | null>(null);
const textarea = ref<HTMLTextAreaElement | null>(null);
let easyMDEInstance: EasyMDE | null = null;

onMounted(async () => {
  if (textarea.value) {
    easyMDEInstance = new EasyMDE({
      element: textarea.value,
      spellChecker: false,
      placeholder: "在这里输入 Markdown...",
      // Add other configurations as needed
    });

    easyMDEInstance.codemirror.on('change', () => {
      if (easyMDEInstance) {
        content.value = easyMDEInstance.value();
      }
    });
  }

  const id = route.params.id;
  if (id) {
    isEditMode.value = true;
    postId.value = id as string;
    try {
      const response = await apiClient.get(`/api/posts/${postId.value}`);
      title.value = response.data.title;
      content.value = response.data.content_markdown;
      if (easyMDEInstance) {
        easyMDEInstance.value(content.value);
      }
    } catch (error) {
      console.error('获取文章失败:', error);
      alert('加载文章数据失败。');
    }
  }
});

// Ensure the editor's value is updated if the ref changes
watch(content, (newValue) => {
    if (easyMDEInstance && easyMDEInstance.value() !== newValue) {
        easyMDEInstance.value(newValue);
    }
});

onUnmounted(() => {
  if (easyMDEInstance) {
    easyMDEInstance.toTextArea();
    easyMDEInstance = null;
  }
});

const savePost = async () => {
  try {
    if (easyMDEInstance) {
      content.value = easyMDEInstance.value();
    }
    const payload = {
      title: title.value,
      content_markdown: content.value,
    };
    if (postId.value) { // The most reliable check
      await apiClient.put(`/api/posts/${postId.value}`, payload);
    } else {
      await apiClient.post('/api/posts', payload);
    }
    router.push('/admin/posts');
  } catch (error) {
    console.error('保存文章失败:', error);
    alert('保存文章失败。');
  }
};
</script>

<template>
  <div class="post-editor">
    <h1>{{ isEditMode ? '编辑文章' : '新建文章' }}</h1>
    <form @submit.prevent="savePost">
      <div class="form-group">
        <label for="title">标题</label>
        <input type="text" id="title" v-model="title" required />
      </div>
      <div class="form-group">
        <label for="content">内容</label>
        <textarea ref="textarea"></textarea>
      </div>
      <div class="form-actions">
        <button type="submit">保存文章</button>
        <button type="button" @click="router.push('/admin/posts')">取消</button>
      </div>
    </form>
  </div>
</template>

<style scoped>
.post-editor {
  max-width: 900px;
  margin: 0 auto;
}
.form-group {
  margin-bottom: 1.5rem;
}
label {
  display: block;
  margin-bottom: 0.5rem;
  font-weight: bold;
}
input[type="text"] {
  width: 100%;
  padding: 0.75rem;
  border: 1px solid var(--color-border);
  background-color: var(--color-background);
  color: var(--color-text);
  border-radius: 4px;
}
.form-actions {
  margin-top: 1.5rem;
}
.form-actions button {
  padding: 0.75rem 1.5rem;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  margin-right: 1rem;
}
.form-actions button[type="submit"] {
  background-color: #28a745;
  color: white;
}
.form-actions button[type="button"] {
  background-color: #6c757d;
  color: white;
}

/* Style EasyMDE to fit the theme */
:deep(.EasyMDEContainer) {
    border-radius: 4px;
    border: 1px solid var(--color-border);
}
:deep(.editor-toolbar) {
    border-top-left-radius: 4px;
    border-top-right-radius: 4px;
    border-bottom: 1px solid var(--color-border);
    background-color: var(--color-background-soft);
}
:deep(.editor-toolbar button) {
    color: var(--color-text);
}
:deep(.editor-toolbar button.active),
:deep(.editor-toolbar button:hover) {
    background: var(--color-background-mute);
    border-color: var(--color-border-hover);
}
:deep(.CodeMirror) {
    background-color: var(--color-background);
    color: var(--color-text);
}
:deep(.CodeMirror-cursor) {
    border-left-color: var(--color-text);
}
:deep(.editor-statusbar) {
    color: var(--color-text-mute);
}
</style>